package com.samskievert.cactusboom;

import java.awt.Color;
import java.awt.Graphics2D;

import com.threerings.media.sprite.ImageSprite;
import java.awt.geom.AffineTransform;

import com.threerings.media.image.BufferedMirage;
import com.threerings.media.image.Mirage;

/**
 * Displays a piece on the board view.
 */
public class CactusSprite extends ImageSprite
{
    /** The dimensions of our sprite in pixels. */
    public static final int SIZE = 48;
    
    /**
     * Creates a piece sprite to display the supplied game piece.
     */
    public CactusSprite (CBObject.Cactus cactus, BufferedMirage image)
    {
        super(image);
        _image = image;
        updateCactus(cactus);
    }

    /**
     * Called when the piece we are displaying has been updated.
     */
    public void updateCactus (CBObject.Cactus cactus)
    {
        // keep track of our piece
        _cactus = cactus;
        
        // set our location based on the location of the piece
        setLocation(_cactus.x * SIZE,_cactus.y * SIZE);

        // force a redraw in case our color changed but not our location
        invalidate();
    }
    
    @Override // from Sprite
    public void paint (Graphics2D gfx)
    {
      
       //draw the cactus spikes
       AffineTransform currentRot = gfx.getTransform();
       int spikes = 0;
       for(int i = 0; i < _cactus.spikes.length; i++)
       { 
            if(_cactus.spikes[i] >= 0) spikes++; 
       }
       double scale = Math.min(1.0,(double)(spikes+1.0) / _cactus.spikes.length);
       gfx.scale(scale,scale);
       //now the sprite will be drawn at (spriteX * scale, spriteY * scale), so we need to correct for that
       gfx.translate((int)(getX() - getX()*scale)/scale,(int)(getY() - getY()*scale)/scale);
       //now we're at the proper x/y coordinate for the TL corner...but we want to be centered!
       int offset = (int)(((SIZE - (SIZE*scale))/2)/scale);
       gfx.translate(offset,offset);
       super.paint(gfx);

       gfx.setTransform(currentRot);

    }
    
    
    public int getCactusKey()
    {
     return _cactus.pieceId;  
    }
    
    public boolean isCactusFull()
    {
     return CBObject.isFull(_cactus);  
    }
    
    private BufferedMirage _image;    
    protected int numSpikes = 0;
    protected CBObject.Cactus _cactus;
}
